package com.travel.travelnetwork.controller.back;

import ch.qos.logback.classic.spi.EventArgUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.travel.travelnetwork.bean.PermissionWithStatus;
import com.travel.travelnetwork.pojo.Role;
import com.travel.travelnetwork.service.PermissionService;
import com.travel.travelnetwork.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping(("/back/role"))
public class RoleController {
    @Autowired
    private RoleService roleService;
    //查询所有角色
    @RequestMapping("/all")
    @PreAuthorize("hasAnyAuthority('/role/all')")
    public ModelAndView all(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10")int size) {
        Page<Role> rolePage = roleService.findPage(page, size);
        ModelAndView mav = new ModelAndView();
        mav.addObject("rolePage", rolePage);
        mav.setViewName("/back/role_all");
        return mav;
    }
    //新增角色
    @RequestMapping("/add")
    public String addRole(Role role) {
        roleService.addRole(role);
        return "redirect:/back/role/all";
    }

    //查询角色
    @RequestMapping("/edit")
    public ModelAndView editRole(Integer rid) {
        ModelAndView mav = new ModelAndView();
        Role role=roleService.findRoleById(rid);
        mav.addObject("role",role);
        mav.setViewName("/back/role_edit");
        return mav;
    }
    //修改角色
    @RequestMapping("/update")
    public String updateRole(Role role) {
        roleService.updateRole(role);
        return "redirect:/back/role/all";
    }

    //删除角色
    @RequestMapping("/delete")
    public String deleteRole(Integer rid) {
        roleService.deleteRole(rid);
        return "redirect:/back/role/all";
    }

    //查看角色权限
    @RequestMapping("/findPermission")
    public ModelAndView findPermission(Integer rid) {
        ModelAndView mav = new ModelAndView();
        List<PermissionWithStatus> allPermissions = roleService.findAllPermissions(rid);
        mav.addObject("allPermissions", allPermissions);
        mav.addObject("rid", rid);
        mav.setViewName("/back/role_permission");
        return mav;
    }

    //修改角色权限
    @RequestMapping("/updatePermission")
    public String updatePermission(Integer rid, Integer[] ids) {
        roleService.roleUpdataPermission(rid, ids);
        return "redirect:/back/role/all";
    }
}
